package com.duan.laugh.sms.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duan.laugh.common.event.constants.EventConstant;
import com.duan.laugh.msg.api.pojo.entity.MsgSend;
import com.duan.laugh.sms.api.entity.SmsAccountSignature;
import com.duan.laugh.sms.api.entity.SmsAccountTemplate;
import com.duan.laugh.sms.api.entity.SmsSend;
import com.duan.laugh.sms.api.entity.SmsSendLog;
import com.duan.laugh.sms.core.SmsAccount;
import com.duan.laugh.sms.core.SmsAccountLocator;
import com.duan.laugh.sms.core.SmsChannelFactory;
import com.duan.laugh.sms.core.SmsRequest;
import com.duan.laugh.sms.mapper.SmsSendMapper;
import com.duan.laugh.sms.service.ISmsAccountSignatureService;
import com.duan.laugh.sms.service.ISmsAccountTemplateService;
import com.duan.laugh.sms.service.ISmsSendLogService;
import com.duan.laugh.sms.service.ISmsSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 短信发送 服务实现类
 * </p>
 *
 * @author liutf
 * @since 2019-11-07
 */
@Slf4j
@Service
public class SmsSendServiceImpl extends ServiceImpl<SmsSendMapper, SmsSend> implements ISmsSendService {

    @Autowired
    private SmsChannelFactory smsChannelFactory;
    @Autowired
    private SmsAccountLocator smsAccountLocator;

    private SmsAccount smsAccount;

    @Autowired
    private ISmsAccountTemplateService smsAccountTemplateService;
    @Autowired
    private ISmsAccountSignatureService smsAccountSignatureService;
    @Autowired
    private ISmsSendLogService smsSendLogService;

    /**
     * 给指定用户推送短信
     *
     * @param msgSend
     */
    @Override
    public void sendSms(MsgSend msgSend) {
        // 短信模版
        Long templateId = msgSend.getTemplateId();
        SmsAccountTemplate smsAccountTemplate = smsAccountTemplateService.getById(templateId);
        // 模版代码
        String templateCode = smsAccountTemplate.getTemplateCode();
        // 短信参数
        String params = msgSend.getParams();
        // 接收人
        String receivePerson = msgSend.getReceiveObjectValue();

        Long accountId = smsAccountTemplate.getAccountId();
        this.smsAccount = smsAccountLocator.getSmsAccount(String.valueOf(accountId));

        // 短信签名
        List<SmsAccountSignature> SmsAccountSignatureList = smsAccountSignatureService.list(new LambdaQueryWrapper<SmsAccountSignature>().eq(SmsAccountSignature::getAccountId, accountId));
        String SignName = "";
        if (CollUtil.isNotEmpty(SmsAccountSignatureList)) {
            SignName = SmsAccountSignatureList.get(0).getName();
        }
        // 改正时间字符串符合安全规范
        String param = this.replaceTime(params);
        smsChannelFactory.getSmsChannel(this.smsAccount.getChannelNameCode().toString())
                .sendSms(this.smsAccount, new SmsRequest()
                        .setMobile(receivePerson)
                        .setTemplate(templateCode)
                        .setSignName(SignName)
                        .setContext(param));
        log.info("短信发送 - 手机号为：【{}】", receivePerson);
        // 存入日志
        smsSendLogService.save(new SmsSendLog()
                .setAccountId(accountId)
                .setTemplateId(templateId)
                .setReceivePersonPhone(receivePerson)
                .setContent(param)
                .setStatus(EventConstant.STATUS_SEND)
                .setSendTime(LocalDateTime.now())
                .setTenantId(msgSend.getTenantId())
                .setCreateTime(LocalDateTime.now()));
    }

    /**
     * 改正时间字符串符合安全规范
     *
     * @param params
     * @return
     */
    private String replaceTime(String params) {
        JSONObject jsonObject = JSONObject.parseObject(params);
        Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
        StringBuilder stringBuilder = null;
        for (Map.Entry<String, Object> entry : entries) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (key.contains("Time")) {
                LocalDateTime dateTime = LocalDateTime.parse(String.valueOf(value));
                LocalDate localDate = dateTime.toLocalDate();
                int year = localDate.getYear();
                int monthValue = localDate.getMonthValue();
                int dayOfMonth = localDate.getDayOfMonth();
                stringBuilder = new StringBuilder();
                stringBuilder.append(year).append("年").append(monthValue).append("月").append(dayOfMonth).append("日");
                jsonObject.put(key, stringBuilder.toString());
            }
        }
        return jsonObject.toJSONString();
    }
}
